import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { Dialog } from 'vant'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login'),
    // 路由元信息，比如存放该路由是否需要登录验证
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/views/layout'),
    children: [
      {
        // 默认子路由
        path: '',
        name: 'home',
        component: () => import('@/views/home'),
        meta: { requiresAuth: false }
      },
      {
        path: 'qa',
        name: 'qa',
        component: () => import('@/views/qa'),
        meta: { requiresAuth: true }
      },
      {
        path: 'my',
        name: 'my',
        component: () => import('@/views/my'),
        meta: { requiresAuth: false }
      },
      {
        path: 'video',
        name: 'video',
        component: () => import('@/views/video'),
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@/views/search'),
    meta: { requiresAuth: false }
  },
  {
    path: '/article/:articleId',
    name: 'article',
    component: () => import('@/views/article'),
    // 将路由中的 params 传递到组件的 props 对象里
    props: true,
    meta: { requiresAuth: false }
  },
  {
    path: '/user/profile',
    name: 'user-profile',
    component: () => import('@/views/user-profile'),
    meta: { requiresAuth: true }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 如果不是 login 路径，需要登录验证未验证（没有用户信息），跳转到登录
  // if (to.path !== '/login' && to.meta.requiresAuth && !store.state.user) {
  //   next({
  //     path: '/login'
  //   })
  // } else {
  //   next()
  // }
  if (to.meta.requiresAuth) {
    // 如果已登录，直接通过
    if (store.state.user) {
      return next()
    }
    Dialog.confirm({
      title: '访问提示',
      message: '该功能需要用户登录，确认登录？'
    })
      // 确认，跳转到登录页
      .then(() => {
        router.replace({
          name: 'login',
          query: {
            redirectPath: router.currentRoute.fullPath
          }
        })
      })
      .catch(() => {
        // 取消，停止路由导航，传入 false
        next(false)
      })
  } else {
    // 不需要登录验证的页面，直接通过
    next()
  }
})

export default router
